import React,{Component} from 'react'
import {Link,Route} from 'react-router-dom'
import Detail from './Detail'

export default class Message extends Component{
  state = {
    messageArr:[
      {id:'01',title:'消息1'},
      {id:'02',title:'消息2'},
      {id:'03',title:'消息3'},
    ]
  }

  //编程式路由导航
  replaceShow = (id,title)=>{
    //实现跳转到Detail组件，且为replace跳转 + 携带params参数
    this.props.history.replace(`/bing/message/detail/${id}/${title}`)

    //search参数和params参数形式差不多
    // this.props.history.replace(`/bing/message/detail/?id={id}&title={title}`)

    //state
    // this.props.history.replace(`/bing/message/detail`,{id,title})   //{id:id,title:title}  ===>   {id,title}
  }
  pushShow = (id,title)=>{
    //实现跳转到Detail组件，且为push跳转 + 携带params参数
    this.props.history.push(`/bing/message/detail/${id}/${title}`)
  }

  // goBack()\goForward()\go()：三种方法，go(n)作用是：当n为正数，如2，则会前进两次，反之则回退
  back = ()=> {
    this.props.history.goBack()
  }
  forward = ()=> {
    this.props.history.goForward()
  }

  render(){
    const {messageArr} = this.state
    return (
      <div className="card">
        <a target="_blank">
          <img src="https://pic4.zhimg.com/v2-6a9a9632a4a2e01bc89bc931b2cb29a1_r.jpg" style={{width: '100px'}}/>
        </a>
        <ul>
          {
            messageArr.map((msgObj)=>{
              return (
                <li key={msgObj.id}>
                  {/* 向路由组件传递 params 参数 */}
                  <Link to={`/bing/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
                  &nbsp;<button onClick={() => this.pushShow(msgObj.id,msgObj.title)}>push查看</button>
                  &nbsp;<button onClick={() => this.replaceShow(msgObj.id,msgObj.title) }>replace查看</button>
                
                  {/* 向路由组件传递 search 参数 */}
                  {/* <Link to={`/bing/message/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link> */}

                  {/* 向路由组件传递 state 参数 */}
                  {/* <Link repalce to={{pathname:'/bing/message/detail',state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link> */}
                  
                </li>
              )
            })
          }
        </ul>
        <hr/>
        {/* 声明接收 params 参数  接收方式：":参数" */}
        <Route path="/bing/message/detail/:id/:title" component={Detail}/>

        {/* search 参数无需声明接收，正常注册路由即可 */}
        {/* <Route path="/bing/message/detail" component={Detail}/> */}

        {/* state 参数无需声明接收，正常注册路由即可 */}
        {/* <Route path="/bing/message/detail" component={Detail}/> */}

        <button onClick={this.back}>回退</button>
        <button onClick={this.forward}>前进</button>

      </div>
    )
  }
}